# -*- coding: utf-8 -*-
import os


class DataUtil:

    def __init__(self, data_dir):
        self.file_paths = []
        self.file_index = 0
        if os.path.isfile(data_dir):
            self.file_paths.append(data_dir)
        else:
            for root, dirs, files in os.walk(data_dir, topdown=False):
                for name in files:
                    if name.endswith("json"):
                        self.file_paths.append(os.path.join(root, name))
        self.current_file = open(self.file_paths[self.file_index], mode="r", encoding="utf-8")

    def next_text(self):
        one_text = self.current_file.read()
        if not one_text:
            while not one_text:
                self.current_file.close()
                self.file_index += 1
                if self.file_index >= len(self.file_paths):
                    break
                self.current_file = open(self.file_paths[self.file_index], mode="r", encoding="utf-8")
                one_text = self.current_file.read()
        # 返回文件路径，以及一篇文本。one_line就是空的时候全部读完。
        return self.current_file.name, one_text

    def next_line(self):
        one_line = self.current_file.readline()
        if not one_line:
            while not one_line:
                self.current_file.close()
                self.file_index += 1
                if self.file_index >= len(self.file_paths):
                    break
                self.current_file = open(self.file_paths[self.file_index], mode="r", encoding="utf-8")
                one_line = self.current_file.readline()
        # 返回文件路径，以及一行。one_line就是空的时候全部读完。
        return self.current_file.name, one_line

    @staticmethod
    def append_result(file_path, line_str):
        with open(file_path, mode="a", encoding="utf-8") as f:
            f.write(line_str+"\n")

    @staticmethod
    def write_results(file_path, line_list):
        with open(file_path, mode="a", encoding="utf-8") as f:
            f.writelines(line_list)

    @staticmethod
    def get_file_dir_name(file_path):
        return os.path.split(file_path)

